# -*- coding:utf-8 -*-
#在UI自动化时，当打印error和critial级别日志时并且截取桌面截图
#但是如果使用以后的Picture模块则会造成Picture和log模块循环调用
#则特写此模块，此模块中只进行桌面截图且不能调用log模块
import os
import time

from PIL import Image
from mss import mss

from ..common.__script_config__ import script_config
from ..common.__const__ import LOG_PATH
from ..report.__remote_log__ import RemoteLogger
from qturboframe.lib.utils.thread_local import main_thread_local


class DesktopPicture(object):
    '''
    获取界面图片

    :Attributes:
     - url: 发送图片到日志服务器的url地址
    '''

    def __init__(self):
        self.url = script_config.remote_log_url

    def get_picture(self):
        '''
        界面截图方法，同时保存图片

        :Args:
         - driver: 用于webui截图，appui、csui截图不需要

        :Returns:
            返回图片地址

        :Example:
         - 例1: path = Picture('webui').get_picture(driver)
         - 例2: path = Picture('csui').get_picture()
         - 例3: path = Picture('appui').get_picture()
        '''
        picture_path = self.__get_screen_pic()
        if picture_path:
            url = RemoteLogger().send_picture(picture_path)
            return url
        return "截图失败"

    def __get_screen_pic(self):
        '''桌面截屏'''
        img_name = self.__get_img_path()
        screen_name = os.path.join(LOG_PATH, img_name)
        # 如果日志目录不存在，则创建目录
        if not os.path.exists(LOG_PATH):
            os.makedirs(LOG_PATH)
        try:
            self.__get_screenshot(screen_name)
        except:
            return "截图失败"
        return screen_name

    def __get_screenshot(self, screen_name):
        with mss() as m:
            rect = m.monitors[0]
            img = m.grab(rect)

            pim = Image.new("RGB", img.size)
            pim.frombytes(img.rgb)
            pim.save(screen_name, quality=95)

            del img, pim

    def __get_img_path(self):
        '''
        创建图片路径

        :Returns:
            返回图片路径的字符串
        '''
        try:
            img_path = time.strftime(main_thread_local.case_id.replace("|", "_") + '_%Y%m%d%H%M%S',
                                     time.localtime(time.time())) + '.png'
        except Exception as e:
            img_path = time.strftime('%Y%m%d%H%M%S',
                                     time.localtime(time.time())) + '.png'
        return img_path
